//
//  DataViewController.swift
//  压岁_IOS
//
//  Created by 梓简王 on 2017/7/12.
//  Copyright © 2017年 梓简王. All rights reserved.
//

import UIKit
import QorumLogs
import TextFieldEffects
import Alamofire

protocol dataViewControllerDelegate{
    func switchAbleTOSide(able:Bool)
    func registerAction()
}

class DataViewController: UIViewController,UITextFieldDelegate,PickerViewDelegete {
    //首页控件
    var dataLabel: UILabel!
    var backColor: UIColor!
    var centerImage: UIImage!
    var delegate:dataViewControllerDelegate?
    var dataObject: String = ""
    var checkBtn: UIButton?
    var nextBtn: UIButton?
    var centerImageView:UIImageView?
    var timer:NSTimer?
    var userMasterRole:Int!
    
    //验证手机号码界面控件
    var userTelTextView: AkiraTextField?
    var userCheckNo: AkiraTextField?
    var sendButton: UIButton!
    var countdownTimer: NSTimer?
    //计数器，倒计时60s的计算
    var remainingSeconds: Int = 0 {
        willSet {
            sendButton.setTitle("\(newValue)  S", forState: .Normal)
            
            if newValue <= 0 {
                sendButton.setTitle("重新获取", forState: .Normal)
                isCounting = false
            }
        }
    }
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTime:", userInfo: nil, repeats: true)
                
                remainingSeconds = 60
                
                sendButton.backgroundColor = UIColor.grayColor()
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                
                sendButton.backgroundColor = UIColor.redColor()
            }
            
            sendButton.enabled = !newValue
        }
    }
    //用户输入姓名密码界面
    var userNameTextView: AkiraTextField?
    var userPassTextView: AkiraTextField?
    //用户输入生日与常住地界面
    var userBirthTextView: AkiraTextField?
    var userAddressTextView: AkiraTextField?
    var picker:DatePickerView?
    
    //控制参数
    var step:Int = 0//0:初始界面 1:验证手机号码界面
    //手机号码确认界面控件位置
    let userPhoneFrame = CGRect(x: 23, y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//输入手机号码位置
    let userCheckNoFrame = CGRect(x: 23, y: 285, width: commonVariable.SYSTEM_WIDTH - 173, height: 60)//输入验证码位置
    
    let sendBtnCenter = CGPoint(x: UIScreen.mainScreen().bounds.width - 86, y: 325)//点击验证位置
    let userPhoneHiddenFrame = CGRect(x: -(commonVariable.SYSTEM_WIDTH - 46), y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//输入手机号码位置
    let userCheckNoHiddenFrame = CGRect(x: -(commonVariable.SYSTEM_WIDTH - 23), y: 285, width: commonVariable.SYSTEM_WIDTH - 173, height: 60)//输入验证码位置
    let sendBtnHiddenCenter = CGPoint(x: -60, y: 325)//点击验证位置
    
    //用户姓名&密码输入界面
    let userNameReadyPosition = CGRect(x: commonVariable.SYSTEM_WIDTH - 69, y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//准备位置
    let userPassReadyPosition = CGRect(x: commonVariable.SYSTEM_WIDTH - 69, y: 285, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//准备位置
    let userNamePosition = CGRect(x: 23, y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//显示位置
    let userPassPosition = CGRect(x: 23, y: 285, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//显示位置
    let userNameHiddenPosition = CGRect(x: -(commonVariable.SYSTEM_WIDTH - 46), y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//影藏位置
    let userPassHiddenPosition = CGRect(x: -(commonVariable.SYSTEM_WIDTH - 46), y: 285, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//隐藏位置
    
    //用户生日与常住地输入界面
    let userBirthReadyPosition = CGRect(x: commonVariable.SYSTEM_WIDTH - 69, y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//准备位置
    let userAddressReadyPosition = CGRect(x: commonVariable.SYSTEM_WIDTH - 69, y: 285, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//准备位置
    let userBirthPosition = CGRect(x: 23, y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//显示位置
    let userAddressPosition = CGRect(x: 23, y: 285, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//显示位置
    let userBirthHiddenPosition = CGRect(x: -(commonVariable.SYSTEM_WIDTH - 46), y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//影藏位置
    let userAddressHiddenPosition = CGRect(x: -(commonVariable.SYSTEM_WIDTH - 46), y: 285, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//隐藏位置
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //添加点击空白收回键盘
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTapBlank:"))
        //创建注册用户
        if(commonVariable.LOCAL_USER == nil){
            commonVariable.LOCAL_USER = User()
        }
        commonVariable.LOCAL_USER?.commonRoleType = "\(self.userMasterRole!)"
        QL4(commonVariable.LOCAL_USER?.commonRoleType)
        //创建中间图片
        centerImageView = UIImageView(frame: CGRectMake(0, 0, 150, 150))
        centerImageView!.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 225)
        centerImageView!.image = self.centerImage
        //创建标题
        self.dataLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        self.dataLabel.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 100)
        self.dataLabel.textAlignment = .Center
        self.dataLabel.font = UIFont(name:commonVariable.ENGLISHFONTNAME, size: 30)
        self.dataLabel!.text = dataObject
        //创建确认按钮
        self.checkBtn = commonTool.initLoginBtn("选 择", rect: CGRect(x: 0, y: 0, width: 100, height: 35),center: CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 400))
        self.checkBtn?.addTarget(self, action: "clickCheckBtn", forControlEvents: UIControlEvents.TouchUpInside)
        self.nextBtn = commonTool.initLoginBtn("确 认", rect: CGRect(x: 0, y: 0, width: 100, height: 35),center: CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 400))
        self.nextBtn?.addTarget(self, action: "clickNextBtn", forControlEvents: UIControlEvents.TouchUpInside)
        self.nextBtn?.alpha = 0
        self.nextBtn?.hidden = true
        self.nextBtn?.userInteractionEnabled = false
        self.view.backgroundColor = backColor
        self.view.addSubview(self.nextBtn!)
        self.view.addSubview(self.checkBtn!)
        self.view.addSubview(self.dataLabel)
        self.view.addSubview(centerImageView!)
        createAllView()
    }
    //MARK: - 创建所有的控件
    func createAllView(){
        //创建手机验证界面对应控件
        self.userTelTextView = AkiraTextField(frame: self.userPhoneFrame)
        self.userTelTextView?.borderColor = commonVariable.IRONCOLOR
        self.userTelTextView?.placeholderColor = commonVariable.IRONCOLOR
        self.userTelTextView?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.userTelTextView?.placeholder = "请输入您的手机"
        
        self.userCheckNo = AkiraTextField(frame: userCheckNoFrame)
        self.userCheckNo?.borderColor = commonVariable.IRONCOLOR
        self.userCheckNo?.placeholderColor = commonVariable.IRONCOLOR
        self.userCheckNo?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.userCheckNo?.placeholder = "请输入验证码"
        
        self.userTelTextView?.delegate = self
        self.userCheckNo?.delegate = self
        
        self.userTelTextView?.inputView = commonVariable.NUMPAD
        self.userCheckNo?.inputView = commonVariable.NUMPAD
        
        //初始化获取验证码选项
        sendButton = UIButton()
        sendButton.frame = CGRect(x: 0, y: 0, width: 107, height: 40)
        sendButton.center = sendBtnCenter
        sendButton.backgroundColor = commonVariable.DEEPREDCOLOR
        sendButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        sendButton.setTitle("获取验证码", forState: .Normal)
        sendButton.titleLabel?.font = UIFont.init(name: commonVariable.CHINAFONTNAME, size: 11)
        sendButton.addTarget(self, action: "sendButtonClick:", forControlEvents: .TouchUpInside)
        
        
        //初始化用户名密码输入界面
        self.userNameTextView = AkiraTextField(frame: self.userNameReadyPosition)
        self.userNameTextView?.borderColor = commonVariable.IRONCOLOR
        self.userNameTextView?.placeholderColor = commonVariable.IRONCOLOR
        self.userNameTextView?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.userNameTextView?.placeholder = "请取一个萌萌的名字"
        
        self.userPassTextView = AkiraTextField(frame: self.userPassReadyPosition)
        self.userPassTextView?.borderColor = commonVariable.IRONCOLOR
        self.userPassTextView?.placeholderColor = commonVariable.IRONCOLOR
        self.userPassTextView?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.userPassTextView?.placeholder = "请输入只有你知道的密码~"
        self.userPassTextView?.keyboardType = UIKeyboardType.ASCIICapable
        
        self.userNameTextView?.delegate = self
        self.userPassTextView?.delegate = self
        
        
        //初始化用户生日与常住地
        self.userBirthTextView = AkiraTextField(frame: self.userBirthReadyPosition)
        self.userBirthTextView?.borderColor = commonVariable.IRONCOLOR
        self.userBirthTextView?.placeholderColor = commonVariable.IRONCOLOR
        self.userBirthTextView?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.userBirthTextView?.placeholder = "点击选择您的破壳日"
        
        self.userAddressTextView = AkiraTextField(frame: self.userAddressReadyPosition)
        self.userAddressTextView?.borderColor = commonVariable.IRONCOLOR
        self.userAddressTextView?.placeholderColor = commonVariable.IRONCOLOR
        self.userAddressTextView?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.userAddressTextView?.placeholder = "点击选择您的家乡"
        
        self.userBirthTextView?.delegate = self
        self.userAddressTextView?.delegate = self
        
        
        self.userNameTextView?.alpha = 0
        self.userPassTextView?.alpha = 0
        self.userBirthTextView?.alpha = 0
        self.userAddressTextView?.alpha = 0
        self.userTelTextView?.alpha = 0
        self.userCheckNo?.alpha = 0
        self.sendButton.alpha = 0
        self.userNameTextView?.userInteractionEnabled = false
        self.userPassTextView?.userInteractionEnabled = false
        self.userBirthTextView?.userInteractionEnabled = false
        self.userAddressTextView?.userInteractionEnabled = false
        self.userTelTextView?.userInteractionEnabled = false
        self.userCheckNo?.userInteractionEnabled = false
        self.sendButton.userInteractionEnabled = false
        self.view.addSubview(userNameTextView!)
        self.view.addSubview(userPassTextView!)
        self.view.addSubview(userBirthTextView!)
        self.view.addSubview(userAddressTextView!)
        self.view.addSubview(sendButton)
        self.view.addSubview(userTelTextView!)
        self.view.addSubview(userCheckNo!)
    }
    
    
    //创建控件(通过step判断删除哪些控件)
    func createViewByStep(){
        QL2("点击了next:\(self.step)")
        switch(step){
        case 0://显示手机验证界面
            //标题、头像、按钮动画移动
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(1.0)
            delegate?.switchAbleTOSide(false)
            self.centerImageView?.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 100)
            self.dataLabel.alpha = 0
            self.checkBtn?.setTitle("取 消", forState: UIControlState.Normal)
            self.checkBtn?.backgroundColor = UIColor.grayColor()
            self.checkBtn?.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/3 - 20, y: 400)
            self.nextBtn?.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/3 * 2 + 20, y: 400)
            self.nextBtn?.hidden = false
            self.nextBtn?.alpha = 1
            self.nextBtn?.userInteractionEnabled = true
            //两个输入框显示
            self.userTelTextView?.alpha = 1
            self.userCheckNo?.alpha = 1
            self.sendButton.alpha = 1
            self.userTelTextView?.userInteractionEnabled = true
            self.userCheckNo?.userInteractionEnabled = true
            self.sendButton.userInteractionEnabled = true
            UIView.commitAnimations()
            //创建后step自加1
            self.step++
            break
        case 1:
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(1.0)
            //隐藏手机确认界面的输入框
            commonVariable.LOCAL_USER?.userTel = self.userTelTextView?.text!
            self.userTelTextView?.frame = self.userPhoneHiddenFrame
            self.userCheckNo?.frame = self.userCheckNoHiddenFrame
            self.sendButton.center = self.sendBtnHiddenCenter
            self.userTelTextView?.alpha = 0
            self.userCheckNo?.alpha = 0
            self.sendButton.alpha = 0
            self.userTelTextView?.userInteractionEnabled = false
            self.userCheckNo?.userInteractionEnabled = false
            self.sendButton.userInteractionEnabled = false
            //显示用户姓名输入控件
            self.userNameTextView?.frame = self.userNamePosition
            self.userPassTextView?.frame = self.userPassPosition
            self.userNameTextView?.alpha = 1
            self.userPassTextView?.alpha = 1
            self.userNameTextView?.userInteractionEnabled = true
            self.userPassTextView?.userInteractionEnabled = true
            UIView.commitAnimations()
            //创建后step自加1
            self.step++
            break
        case 2:
            //判断用户名和密码是否填写
            if self.userNameTextView!.text == "" || self.userPassTextView!.text == "" {
                SweetAlert().showAlert("宝贝~", subTitle: "请填写完成本页信息", style: AlertStyle.Warning)
                return
            }
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(1.0)
            //隐藏用户名字与密码的输入框
            commonVariable.LOCAL_USER?.userName = self.userNameTextView?.text!
            commonVariable.LOCAL_USER?.userPass = self.userPassTextView?.text!
            self.userNameTextView?.frame = self.userNameHiddenPosition
            self.userPassTextView?.frame = self.userPassHiddenPosition
            self.userNameTextView?.alpha = 0
            self.userPassTextView?.alpha = 0
            self.userNameTextView?.userInteractionEnabled = false
            self.userPassTextView?.userInteractionEnabled = false
            //显示用户日期输入控件
            self.userBirthTextView?.frame = self.userBirthPosition
            self.userAddressTextView?.frame = self.userAddressPosition
            self.userBirthTextView?.alpha = 1
            self.userAddressTextView?.alpha = 1
            self.userBirthTextView?.userInteractionEnabled = true
            self.userAddressTextView?.userInteractionEnabled = true
            UIView.commitAnimations()
            self.nextBtn?.setTitle("注 册", forState: UIControlState.Normal)
            //创建后step自加1
            self.step++
            break
        case 3:
            if self.userBirthTextView!.text == "" || self.userAddressTextView!.text == "" {
                SweetAlert().showAlert("宝贝~", subTitle: "请填写完成本页信息", style: AlertStyle.Warning)
                return
            }
            commonVariable.LOCAL_USER?.userBirth = self.userBirthTextView?.text!
            commonVariable.LOCAL_USER?.userAddress = self.userAddressTextView?.text!
            userRegister()
            break
        default:
            //创建后step自加1
            self.step++
            QL2("点击了next发生break:\(self.step)")
            return
        }
    }
    
    //MARK: - 获取验证码方法
    func sendButtonClick(sender: UIButton) {
        //下面获取验证码
        if (self.userTelTextView!.text == "" ) {
            SweetAlert().showAlert("宝贝~", subTitle: "请输入您的手机号码！", style: AlertStyle.Warning)
        }else{
            self.isCounting = true
            let telNo = self.userTelTextView!.text as! NSString
            SMSSDK.getVerificationCodeByMethod(SMSGetCodeMethodSMS, phoneNumber: telNo as String, zone: "86", result: { (error:NSError!) -> Void in
                if(error == nil){
                    QL2("发送成功")
                }else {
                    self.isCounting = false
                    switch error.code {
                    case 457:
                        SweetAlert().showAlert("宝贝~", subTitle: "您输入的号码有误！", style: AlertStyle.Warning)
                    case 477:
                        SweetAlert().showAlert("宝贝~", subTitle: "对不起，当前手机号码今日发送过多，请明日再尝试！", style: AlertStyle.Warning)
                    default :
                        SweetAlert().showAlert("宝贝~", subTitle: "出现未知错误！", style: AlertStyle.Warning)
                    }
                    QL2("发送失败")
                }
            })
        }
    }
    func updateTime(timer: NSTimer) {
        remainingSeconds -= 1
    }
    //点击左边的按钮
    func clickCheckBtn(){
        QL2("点击了front:\(self.step)")
//        getAllSchoolList.getPROVINCE()
        switch(step){
        case 0:
            createViewByStep()
            return
        case 1:
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(1.0)
            delegate?.switchAbleTOSide(true)//允许滑动
            self.centerImageView?.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 225)
            self.dataLabel.alpha = 1
            self.checkBtn?.setTitle("选 择", forState: UIControlState.Normal)
            self.checkBtn?.backgroundColor = commonVariable.BLUECOLOR
            self.checkBtn?.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 400)
            self.nextBtn?.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 400)
            self.nextBtn?.hidden = true
            self.nextBtn?.alpha = 0
            self.sendButton.alpha = 0
            self.userTelTextView?.alpha = 0
            self.userCheckNo?.alpha = 0
            self.nextBtn?.userInteractionEnabled = false
            UIView.commitAnimations()
            break
        case 2:
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(1.0)
            //隐藏用户姓名及密码
            self.userNameTextView?.frame = self.userNameReadyPosition
            self.userPassTextView?.frame = self.userPassReadyPosition
            self.userNameTextView?.alpha = 0
            self.userPassTextView?.alpha = 0
            self.userNameTextView?.userInteractionEnabled = false
            self.userPassTextView?.userInteractionEnabled = false
            //显示确认密码界面的输入框
            self.userTelTextView?.frame = self.userPhoneFrame
            self.userCheckNo?.frame = self.userCheckNoFrame
            self.sendButton.center = self.sendBtnCenter
            self.userTelTextView?.alpha = 1
            self.userCheckNo?.alpha = 1
            self.sendButton.alpha = 1
            self.userTelTextView?.userInteractionEnabled = true
            self.userCheckNo?.userInteractionEnabled = true
            self.sendButton.userInteractionEnabled = true
            
            UIView.commitAnimations()
            break
        case 3:
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(1.0)
            //隐藏用户地址输入框
            self.userBirthTextView?.frame = self.userBirthReadyPosition
            self.userAddressTextView?.frame = self.userAddressReadyPosition
            self.userBirthTextView?.alpha = 0
            self.userAddressTextView?.alpha = 0
            self.userBirthTextView?.userInteractionEnabled = false
            self.userAddressTextView?.userInteractionEnabled = false
            self.nextBtn?.setTitle("确 认", forState: UIControlState.Normal)
            //显示用户输入名字
            self.userNameTextView?.frame = self.userNamePosition
            self.userPassTextView?.frame = self.userPassPosition
            self.userNameTextView?.alpha = 1
            self.userPassTextView?.alpha = 1
            self.userNameTextView?.userInteractionEnabled = true
            self.userPassTextView?.userInteractionEnabled = true
            UIView.commitAnimations()
            break
        default:
            QL2("点击了front发生break:\(self.step)")
            return
        }
        //删除后step自减1
        self.step--
    }
    func clickNextBtn(){
        switch(step){
        case 0:
            break
        case 1:
            //验证手机号码
            checkThePhone()
            break
        default:
            createViewByStep()
            break
        }
    }
    //用户注册模块
    func userRegister(){
        //这边直接注册成功，等到接口写好后在这边验证
        commonVariable.LOCAL_USER?.userName = userNameTextView?.text!
        commonVariable.LOCAL_USER?.userTel = userTelTextView?.text!
        commonVariable.LOCAL_USER?.userAddress = userAddressTextView?.text!
        commonVariable.LOCAL_USER?.userBirth = userBirthTextView?.text!
        commonVariable.LOCAL_USER?.commonRoleType = "\(self.userMasterRole!)"
        commonVariable.LOCAL_USER?.registerationTime = commonTool.getUnixTime()
        let body = commonVariable.LOCAL_USER?.toDict() as! [String:String]
        QL4(body)
        Alamofire.request(.POST, commonVariable.USERREGISTERATION,parameters:body).responseJSON() {
            response in
            guard let JSONDIC = response.result.value else {
                QL4(response.result.error)
                switch response.result.error!.code {
                case -1009 :
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                case 3840:
                    SweetAlert().showAlert("对不起", subTitle: "服务出现故障，请联系管理员", style: AlertStyle.Error)
                case -1001 :
                    
                    SweetAlert().showAlert("对不起", subTitle: "上传信息超时", style: AlertStyle.Error)
                default:
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                }
                return }
            QL2(JSONDIC)
            let resultDict = JSONDIC as? NSDictionary
            let jsonObj = JSON(JSONDIC)
            let errorCode = jsonObj["errorcode"].intValue
            let errorMsg = jsonObj["message"].stringValue
            QL2(errorMsg)
            if errorCode != 1 {
                SweetAlert().showAlert("对不起", subTitle: "\(errorMsg)", style: AlertStyle.Warning)
            }else{
                self.delegate!.registerAction()
            }
        }
    }
    
    //验证手机与验证码
    func checkThePhone(){
        //测试则直接通过
        if(commonVariable.ISCHECK){
            self.createViewByStep()
            return
        }
        //下面进行验证
        let telNo = self.userTelTextView!.text
        let checkNo = self.userCheckNo!.text
        if checkNo == "" {
            SweetAlert().showAlert("宝贝~", subTitle: "请输入验证码！", style: AlertStyle.Warning)
        }else{
            SMSSDK.commitVerificationCode(checkNo, phoneNumber: telNo, zone: "86", result: { (error:NSError!) -> Void in
                if error == nil {
                    //验证成功
                    self.createViewByStep()
                }else{
                    SweetAlert().showAlert("宝贝~", subTitle: "你输入的验证码有小瑕疵哦~", style: AlertStyle.Error)
                }
            })
        }
    }
    //对输入进行检测
    func textFieldDidEndEditing(textField: UITextField) {
        //对用户名和密码进行限制
        if textField == self.userTelTextView  && userTelTextView!.text != ""{
            var length = self.userTelTextView!.text!.characters.count
            if length != 11 {
                SweetAlert().showAlert("宝贝~", subTitle: "请输入您的11位手机号码！", style: AlertStyle.Warning)
                self.userTelTextView!.text = ""
                textField.resignFirstResponder()
            }
            return
        }
        if textField == self.userCheckNo  && userCheckNo!.text?.characters.count == 4{
            checkThePhone()
            textField.resignFirstResponder()
            return
        }
        
        //对用户名和密码进行限制
        if textField == self.userNameTextView  && textField.text != ""{
            var length = 0
            for char in self.userNameTextView!.text!.characters {
                // 判断是否中文，是中文+2 ，不是+1
                length += "\(char)".lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 3 ? 2 : 1
            }
            if length < 6 {
                SweetAlert().showAlert("用户名必须大于三个中文字符或6个英文字符")
                self.userNameTextView!.text = ""
                textField.resignFirstResponder()
            }else if length > 16 {
                SweetAlert().showAlert("用户名不能大于8个中文字符或16个英文字符")
                self.userNameTextView!.text = ""
                textField.resignFirstResponder()
            }
            return
        }
        if textField == self.userPassTextView  && textField.text != ""{
            var length = 0
            for char in self.userPassTextView!.text!.characters {
                // 判断是否中文，是中文+2 ，不是+1
                length += "\(char)".lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 3 ? 2 : 1
            }
            if length < 8 {
                SweetAlert().showAlert("密码必须大于8个英文字符")
                self.userPassTextView!.text = ""
                textField.resignFirstResponder()
            }else if length > 13 {
                SweetAlert().showAlert("密码不可以大于13个英文字符")
                self.userPassTextView!.text = ""
                textField.resignFirstResponder()
            }
            return
        }
    }
    //MARK: -textfield代理实现
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    //对user常驻地text点击进行监控
    func textFieldDidBeginEditing(textField: UITextField) {
        if textField == userAddressTextView {
            self.userAddressTextView!.resignFirstResponder()
            showCitySelect()
        }else if textField == userBirthTextView {
            self.userBirthTextView!.resignFirstResponder()
            showDataPickView()
        }
    }
    //居住地选择
    func showCitySelect(){
        let tempData = UIScreen.mainScreen().bounds.size
        var pickView = AreaPickView.init(frame: CGRectMake(20, tempData.height/2-110, tempData.width - 40, 220))
        pickView.delegate = self
        pickView.show()
    }
    func pickerDidSelectName(name: String!) {
        self.userAddressTextView!.text = name
    }
    func cancelBtn() {
        self.userAddressTextView!.text = nil
    }
    //日期选择
    func showDataPickView(){
        picker = DatePickerView.getShareInstance()
        picker!.textColor = UIColor.redColor()
        picker!.showWithDate(NSDate())
        picker?.block = {
            (date:NSDate)->() in
            let formatter = NSDateFormatter()
            formatter.dateFormat = "yyyy-MM-dd zzz"
            let string = formatter.stringFromDate(date)
            let range:Range = string.rangeOfString(" ")!
            let time = string.substringToIndex(range.endIndex)
            self.userBirthTextView!.text = time
        }
        picker?.cancelBlock = {
            ()->() in
            //是的取消的时候置空，而不是“”
            self.userBirthTextView!.text = nil
        }
    }
    //点击空白响应
    func handleTapBlank(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
            if (userTelTextView != nil){            
                self.userTelTextView!.resignFirstResponder()
                self.userCheckNo!.resignFirstResponder()
                self.userNameTextView?.resignFirstResponder()
                self.userPassTextView?.resignFirstResponder()
            }
        }
        sender.cancelsTouchesInView = false
    }
}

